package controllers.webapi

import akka.actor.ActorSystem
import controllers.KingdeeWebApi

import javax.inject._
import play.api.Logging
import play.api.mvc._
import services.mes.MoreMesService
import play.api.libs.json.{JsValue, Json}
import services.kingdee.KindeeBaseInfoSync

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class WebApiController @Inject()(
                                  cc: ControllerComponents,
                                  kdWebApi: KingdeeWebApi,
                                  moreMesSrv: MoreMesService,
                                  baseSync: KindeeBaseInfoSync
                                )(implicit exec: ExecutionContext)
  extends AbstractController(cc)
    with Logging {

  def index = kdWebApi.index

  def show(page: String) = kdWebApi.show(page)

  def webApi(apiUrl: String) = kdWebApi.webApi(apiUrl)

  def receive = Action {
    Ok("received")
  }

  def operation() = Action.async { implicit request =>
    val dataModel: JsValue = request.body match {
      case a: AnyContentAsJson => {
        logger.debug(s"body is AnyContentAsJson:\n${a.asJson.get.toString()}")
        a.asJson.get
      }
      case a: AnyContentAsRaw => {
        logger.debug(s"body is AnyContentAsRaw:\n${a.asRaw.get.asBytes().get.decodeString("UTF8")}")
        Json.parse(a.asRaw.get.asBytes().get.decodeString("UTF8"))
      }
      case a: AnyContentAsText => {
        logger.debug(s"body is AnyContentAsText\n${a.asText}")
        Json.parse(a.asText.get)
      }
      case _ => {
        logger.info(s"body is ${request.body.getClass},contentType: ${request.contentType}")
        Json.obj("parameters" -> Json.arr(""))
      }
    }
    router(dataModel).map { res =>
      logger.debug(s"operation(${dataModel.toString})=> $res")
      Ok(res)
    }
  }

  /**
   * @param jsData
   * {"accid":"32424234","formid":"mo","op":"delete","order":"DJS0001"}
   */
  def router(jsData: JsValue) = {
    try {
      val accid = (jsData \ "accid").as[String]
      val op = (jsData \ "op").as[String]
      val formid = (jsData \ "formid").as[String]
      val order = (jsData \ "order").as[String]
      op match {
        case "delete" => moreMesSrv.deleteOrder(accid = accid, formid = formid, order = order)
        case "sync" => moreMesSrv.syncOrder(accid = accid, otype = formid, order = order)
        case "otype" => moreMesSrv.getOtype()
        case "sync2ld" => baseSync.manyOperation(accid = accid, formid = formid, codes = order)
        case _ => Future(s"($op) not in [delete,sync]")
      }
    } catch {
      case e: Exception => logger.error(s"router($jsData)", e); Future("post data error")
    }

  }


}
